'use strict';

const Service = require('egg').Service;
const fs = require('fs');
const path = require('path');

class PdfResumeService extends Service {
  /**
   * 上传PDF简历
   */
  async uploadPdfResume(file, userId = 1) {
    const { ctx } = this;

    try {
      // 确保上传目录存在
      const uploadDir = path.join(this.app.baseDir, 'app/public/pdf_resume');
      if (!fs.existsSync(uploadDir)) {
        fs.mkdirSync(uploadDir, { recursive: true });
      }

      // 获取原始文件名
      const originalFilename = file.filename;
      
      // 检查文件是否已存在，如果存在则添加时间戳
      let finalFilename = originalFilename;
      let targetPath = path.join(uploadDir, finalFilename);
      
      if (fs.existsSync(targetPath)) {
        const timestamp = Date.now();
        const ext = path.extname(originalFilename);
        const nameWithoutExt = path.basename(originalFilename, ext);
        finalFilename = `${nameWithoutExt}_${timestamp}${ext}`;
        targetPath = path.join(uploadDir, finalFilename);
      }

      // 移动文件到目标位置
      const readStream = fs.createReadStream(file.filepath);
      const writeStream = fs.createWriteStream(targetPath);
      
      await new Promise((resolve, reject) => {
        readStream.pipe(writeStream);
        writeStream.on('finish', resolve);
        writeStream.on('error', reject);
      });

      // 删除临时文件
      fs.unlinkSync(file.filepath);

      // 构建访问URL
      const fileUrl = `/public/pdf_resume/${finalFilename}`;
      
      // 保存到数据库
      const pdfResume = await ctx.model.PdfResume.create({
        user_id: userId,
        file_name: originalFilename, // 保存原始文件名
        file_path: targetPath,
        file_size: fs.statSync(targetPath).size,
        file_url: fileUrl,
        status: 1
      });

      return pdfResume;
    } catch (error) {
      ctx.logger.error('上传PDF简历失败:', error);
      throw error;
    }
  }

  /**
   * 获取PDF简历列表
   */
  async getPdfResumeList(query = {}) {
    const { ctx } = this;
    const { page = 1, pageSize = 100, user_id } = query;
    const offset = (page - 1) * pageSize;

<<<<<<< HEAD
=======
    // 设置where条件
>>>>>>> resume
    const where = { status: 1 };
    if (user_id) {
      where.user_id = user_id;
    }
<<<<<<< HEAD
=======
    // 管理员可以查看所有PDF简历（不设置user_id过滤）
>>>>>>> resume

    const result = await ctx.model.PdfResume.findAndCountAll({
      where,
      limit: parseInt(pageSize),
      offset: parseInt(offset),
      order: [['created_at', 'DESC']]
    });

    return {
      total: result.count,
      page: parseInt(page),
      pageSize: parseInt(pageSize),
      list: result.rows
    };
  }

  /**
   * 获取PDF简历详情
   */
  async getPdfResumeById(id) {
    const { ctx } = this;
    const pdfResume = await ctx.model.PdfResume.findOne({
      where: { id, status: 1 }
    });

    if (!pdfResume) {
      ctx.throw(404, 'PDF简历不存在');
    }

    return pdfResume;
  }

  /**
   * 删除PDF简历
   */
  async deletePdfResume(id) {
    const { ctx } = this;

    const pdfResume = await this.getPdfResumeById(id);

    // 删除物理文件
    if (fs.existsSync(pdfResume.file_path)) {
      fs.unlinkSync(pdfResume.file_path);
    }

    // 从数据库删除（软删除）
    await ctx.model.PdfResume.update(
      { status: 0 },
      { where: { id } }
    );

    return true;
  }
}

module.exports = PdfResumeService;

